package com.xm.ojcodesandbox.utils;

import com.xm.ojcodesandbox.model.ExecuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;


/**
 * 进程工具类
 */
public class ProcessUtils {
    public static ExecuteMessage getExecuteMessage(Process process, String op) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            int exitValue = process.waitFor();
            StringBuilder message = new StringBuilder();
            StringBuilder errorMessage = new StringBuilder();
            //正常退出
            if (exitValue == 0) {
                System.out.println(op + "成功");
                //分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String outputLine;
                while ((outputLine = bufferedReader.readLine()) != null) {
                    message.append(outputLine);
                }
                System.out.println(message);
            } else {
                System.out.println(op + "失败, 错误码： " + exitValue);
                //分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder appendString = new StringBuilder();
                String outputLine;
                while ((outputLine = bufferedReader.readLine()) != null) {
                    appendString.append(outputLine).append("\n");
                }
                System.out.println(appendString);
                //分批获取进程的输出
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                String erroroutputLine;
                while ((erroroutputLine = errorBufferedReader.readLine()) != null) {
                    errorMessage.append(erroroutputLine).append("\n");
                }
                System.out.println(errorMessage);
            }
            executeMessage.setExitValue(exitValue);
            executeMessage.setMessage(String.valueOf(message));
            executeMessage.setErrorMessage(String.valueOf(errorMessage));

            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (Exception e) {

        }
        return executeMessage;
    }
}
